package com.transcendence.appwidget.twofour;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.jinrishici.sdk.android.JinrishiciClient;
import com.jinrishici.sdk.android.listener.JinrishiciCallback;
import com.jinrishici.sdk.android.model.JinrishiciRuntimeException;
import com.jinrishici.sdk.android.model.PoetySentence;
import com.transcendence.appwidget.R;
import com.transcendence.appwidget.WidgetUpdateListener;
import com.transcendence.appwidget.twofive.MyService;
import com.transcendence.appwidget.twofive.TwoFiveAppWidget;
import com.transcendence.core.global.Global;
import com.transcendence.core.utils.date.DateUtils;
import com.transcendence.core.utils.log.LogUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author joephone
 * @date 2023/10/27
 * @desc
 */
public class TwoFourAppWidget extends AppWidgetProvider  {

    private static final int MAX_SIZE = 3;
    private final List<String> mCache = new ArrayList<>(MAX_SIZE);

    private static final int UPDATE_UNLOGIN = 0x123;
    private static final int UPDATE_LOGIN = 0x124;
    private Context mContext;
    private AppWidgetManager mAppWidgetManager;
    private int[] mAppWidgetIds;

    private MyServiceConnection mServiceConnection;
//    private WidgetUpdateListenerImpl mListenerImpl;  // 保存WidgetUpdateListener接口实例


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_UNLOGIN:
                    // 更新UI
                    updateText();
                    break;
            }
        }
    };

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        mContext = context;
        mServiceConnection = new MyServiceConnection(context);

        Intent intent = new Intent(context, MyService.class);
        intent.setAction("com.transcendence.core.action.LOGIN");
        intent.setPackage("com.transcendence.appwidget");
        context.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    // 小部件从桌面移除时，解绑Service
    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
        if (mServiceConnection != null) {
            context.unbindService(mServiceConnection);
            mServiceConnection = null;
        }
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        LogUtils.d("TwoFourAppWidget onUpdate");
        mContext = context;
        mAppWidgetManager = appWidgetManager;
        mAppWidgetIds = appWidgetIds;
        updateWidgetView();  //context,appWidgetManager ,appWidgetIds
    }

    /**
     * 接收窗口小部件点击时发送的广播
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        LogUtils.d("TwoFiveAppWidget onReceive");
        if(intent!=null && !TextUtils.isEmpty(intent.getAction())){
            switch (intent.getAction()){
                case Global.REFRESH_CLICK_ACTION:
                    LogUtils.d("onReceive REFRESH_CLICK_ACTION");
                    request(context);
                    break;
                case Global.REFRESH_LOGIN:
                    LogUtils.d("onReceive REFRESH_LOGIN");

                    request(context);
                    break;
            }
        }
    }

    private void updateWidgetView() {  //Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds
        RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.layout_two_four);

        views.setViewVisibility(
                R.id.iv_ad,
                View.VISIBLE
        );

        // 设置按钮点击事件
        views.setOnClickPendingIntent(
                R.id.tv_edit,
                registerRefreshAction(mContext)
        );

//        Glide.with(mContext.getApplicationContext())
//                .asBitmap()
//                .load("https://app-lcbqiniu.dfpv.com.cn/Fp0NJYFOZix54ly7vGbG7LpHt-QS")
//                .into(new CustomTarget<Bitmap>() {
//                    @Override
//                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                        LogUtils.d("onResourceReady");
//                        RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.layout_two_four);
//                        remoteViews.setImageViewBitmap(R.id.iv_ad,getRoundedCornerBitmap(resource,16));   //getRoundedCornerBitmap(resource,80)
//                        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
//                        ComponentName appWidgetIds = new ComponentName(mContext, TwoFourAppWidget.class);
//                        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
//                    }
//
//                    @Override
//                    public void onLoadCleared(@Nullable Drawable placeholder) {
//                        // Handle cleanup here
//                    }
//                });

        for (int appWidgetId : mAppWidgetIds) {
            mAppWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }

    private void request(Context context) {
        mContext = context;
        LogUtils.d("TwoFiveAppWidget---------------request---------------今日诗词");
        JinrishiciClient client = JinrishiciClient.getInstance();
        client.getOneSentenceBackground(new JinrishiciCallback() {
            @Override
            public void done(PoetySentence data) {
                LogUtils.d("今日诗词---------------"+data.getData().getContent());
                mCache.add(data.getData().getContent());
                sendMsgUpdateUI();
            }

            @Override
            public void error(JinrishiciRuntimeException e) {
                LogUtils.d("error: code = " + e.getCode() + " message = " + e.getMessage());
            }
        });
    }

    private void sendMsgUpdateUI() {
        Message msg = mHandler.obtainMessage();
        msg.what = UPDATE_UNLOGIN;
        mHandler.sendMessage(msg);
    }


    public String getShici() {
        if (mCache.isEmpty()) {
            return null;
        }
        return mCache.get(0);
    }

    private void updateText() {
        LogUtils.d("更新UI");
        RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.layout_two_four);
        remoteViews.setTextViewText(R.id.tv_name_car,getShici());

        remoteViews.setTextViewText(R.id.tv_date_time,getDateTime());
        String url = "https://app-lcbqiniu.dfpv.com.cn/Fp0NJYFOZix54ly7vGbG7LpHt-QS";


        Glide.with(mContext.getApplicationContext())
                .asBitmap()
                .load("https://app-lcbqiniu.dfpv.com.cn/Fp0NJYFOZix54ly7vGbG7LpHt-QS")
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        LogUtils.d("onResourceReady");
                        RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.layout_two_four);
                        remoteViews.setImageViewBitmap(R.id.iv_ad,getRoundedCornerBitmap(resource,16));   //getRoundedCornerBitmap(resource,80)
                        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
                        ComponentName appWidgetIds = new ComponentName(mContext, TwoFourAppWidget.class);
                        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                        // Handle cleanup here
                    }
                });


        AppWidgetManager manager = AppWidgetManager.getInstance(mContext);
        ComponentName componentName = new ComponentName(mContext, TwoFourAppWidget.class);
        manager.updateAppWidget(componentName,remoteViews);
    }

    private String getDateTime(){
        return DateUtils.getInstance().formatDate12String(System.currentTimeMillis()+"");
    }


    private PendingIntent registerRefreshAction(Context context) {
        //注册广播
        Intent intent = new Intent(Global.REFRESH_CLICK_ACTION);
        ComponentName componentName = new ComponentName(context,TwoFourAppWidget.class);
        intent.setComponent(componentName);

        return PendingIntent.getBroadcast(
                context,
                R.id.tv_edit,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
    }

    private void isShowUnLoginBottom(RemoteViews views,int state){
        views.setViewVisibility(
                R.id.ll_bottom_unlogin,
                state
        );
    }

    public Bitmap getRoundedCornerBitmap(Bitmap bitmap,int radius) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        paint.setShader(shader);
        canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius, paint);
        return output;
    }


//    // 内部类，用于实现WidgetUpdateListener接口
//    private class WidgetUpdateListenerImpl extends WidgetUpdateListener.Stub {
//        @Override
//        public void onUpdateWidget() throws RemoteException {
//            // 接收到通知后，执行更新UI的操作
//            updateWidgetView();
//        }
//    }

    // Service连接对象，用于获取WidgetUpdateListener接口实例
    private class MyServiceConnection implements ServiceConnection {
        private final Context mContext;
        private WidgetUpdateListener mListener;

        public MyServiceConnection(Context context) {
            mContext = context;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtils.d("MyServiceConnection onServiceConnected");
            mListener = WidgetUpdateListener.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mListener = null;
        }
    }
}
